package space.xxhui.principleof6.Adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.List;

import space.xxhui.principleof6.R;
import space.xxhui.principleof6.interfaces.IImageCache;
import space.xxhui.principleof6.interfaces.IImageFactory;
import space.xxhui.principleof6.utils.ImageAsyncTask;
import space.xxhui.principleof6.utils.ParsingConfig;


/**
 * Created by hui on 2016/10/12.
 */

public class ImageAdapter extends RecyclerView.Adapter {

    private static final String TAG = "ImageAdapter";
    private List data;
    private Context context;
    private IImageCache iImageCache;
    private IImageFactory iImageFactory;

    public ImageAdapter(Context context, List data) {
        this.context = context.getApplicationContext();
        this.data = data;
        iImageFactory = ParsingConfig.getBean(context);
        iImageCache = iImageFactory.createImageCache(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Bitmap lruBitmap = iImageCache.getBitmap(String.valueOf(data.get(position)));
        if (lruBitmap == null) {
            ImageAsyncTask task = new ImageAsyncTask(iImageCache,((ViewHolder) holder).imageView, context);
            task.execute(String.valueOf(data.get(position)));
        }
        ((ViewHolder) holder).imageView.setImageBitmap(lruBitmap);

        Log.e(TAG, "onBindViewHolder: " + position, null);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;

        public ViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView;
        }
    }


}
